package cn.onesdream.app.api.controller;

import cn.onesdream.app.api.service.CardService;
import cn.onesdream.app.common.util.ResponseResult;
import cn.onesdream.app.dao.entity.Card;
import cn.onesdream.app.dao.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * @author WangShiyu
 * @date 2021/2/7 0:32
 */
@RestController
@RequestMapping("/api/card")
@Slf4j
@Api(tags = "卡片相关接口")
@Validated
public class CardController {
    @Autowired
    private CardService cardService;


    @ApiOperation("通过id数组获取卡片列表")
    @PostMapping("/getPlanetList")
    public ResponseResult<List> getCardList(Integer[] cardId){
        List<Card> cardList = cardService.getCardList(cardId);
        return new ResponseResult<>(cardList);
    }

    @ApiOperation("删除卡片")
    @PostMapping("/deleteCard")
    public ResponseResult<Card> deleteCard(Integer cardId) {
        cardService.deleteCard(cardId);
        return new ResponseResult<>();
    }

    @ApiOperation("通过planetId获取卡片信息")
    @GetMapping("/getCardByPlanetId/{planetId}")
    public ResponseResult<List> getCardByPlanetId(@PathVariable("planetId") @NotNull Integer planetId){
        List<Card> cardList = cardService.getCardByPlanetId(planetId);
        return new ResponseResult<>(cardList);
    }

    @ApiOperation("修改卡片信息")
    @PostMapping("/changeCardInfo")
    public ResponseResult<Card> changeCardInfo(
            Integer cardId,
            String title,
            String content,
            MultipartFile[] pictures,
            Byte nameless) throws IOException {
        Card card = cardService.changeCardInfo(cardId, title, content, pictures, nameless);
        return new ResponseResult<>(card);
    }
    @ApiOperation("获得指定卡片")
    @GetMapping("/{cardId}")
    public ResponseResult<Card> card(@PathVariable("cardId") @NotNull Integer cardId){
        Card card = cardService.getCard(cardId);
        return new ResponseResult<>(card);
    }

    @ApiOperation("发表卡片")
    @PostMapping("/")
    @ApiImplicitParam(name = "nameless", value = "不传时默认为 0：不匿名")
    public ResponseResult<Card> postCard(String title, String content, Integer planetId, MultipartFile[] pictures, Byte nameless)throws IOException {
        Integer userId = ((User) SecurityContextHolder.getContextHolderStrategy().getContext().getAuthentication().getPrincipal()).getId();
        cardService.addCard(title, content, userId, planetId, pictures, nameless);
        return new ResponseResult<>();
    }

}
